﻿# encoding:utf-8
# 访问数据库 base
import pymysql

import sys
sys.path.append("../..")
from wxpyImport import *

# 数据库结构体，为了能在方法内的修改返回到方法外
class dbData:
    def __init__(self):
        self.db = getDb()

# 连数据库
def getDb():
    try:
        # 打开数据库连接
        db = pymysql.connect(
            host='localhost',
            port=3306,
            user='root',
            passwd='0026888',
            db='wxpy_unique_puid',
            charset='utf8'
        )
    except Exception as e:
        dealException()
        logError('getDb err: '+str(e))
        return None
    
    logError('getDb: '+str(db))
    return db

def closeDb(dbd):
    try:
        logError('closeDb: '+str(dbd.db))
        dbd.db.close()
    except Exception as e:
        dealException()
        logError('closeDb err: '+str(e))

def getCursor(dbd, resetDb=False):
    try:
        return dbd.db.cursor()
    except Exception as e:
        dealException()
        logError('getCursor err: '+str(e))
        if resetDb:
            closeDb(dbd)
            dbd.db = getDb()
            return dbd.db.cursor()

# 读出的数据中包含列名 
def getCursorColName(dbd, resetDb=False):
    try:
        return dbd.db.cursor(cursor=pymysql.cursors.DictCursor)
    except Exception as e:
        dealException()
        logError('getCursorColName err: '+str(e))
        if resetDb:
            closeDb(dbd)
            dbd.db = getDb()
            return dbd.db.cursor(cursor=pymysql.cursors.DictCursor)